<template>
  <div class="form-preview">
    <div class="header">
      <div class="question-name">{{ questionName }}</div>
    </div>
    <div class="preview-box">
      <!-- 表单预览容器 -->
      <el-form class="preview-canvas" :model="previewData" ref="formRef">
        <div
          v-for="item in components.filter((c) => !c.parentId)"
          :key="item.id"
          class="preview-component"
          v-show="!isComponentHidden(item.id)"
          :style="getComponentStyle(item)"
        >
          <FormComponent
            :component="{
              ...item,
              value: previewData[item.props?.field],
            }"
            :mutex-state="mutexState"
            :is-preview="true"
          />
        </div>
      </el-form>
    </div>
    <div class="actions">
      <el-button @click="handleReset(formRef)">重置表单</el-button>
      <el-button @click="handleSubmit(formRef)" type="primary"
        >提交表单</el-button
      >
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance } from "element-plus";
import FormComponent from "../lowCode/components/FormComponent.vue";
import type {
  CanvasComponent,
  MutexRule,
  RelateConfig,
} from "../lowCode/types";
import { getQuestionById } from "@/api/home";
import { useRoute } from "vue-router";
import { EventBus } from "@/utils/eventBus";

const emit = defineEmits<{
  submit: [data: Record<string, any>];
}>();

// 组件挂载时初始化
onMounted(() => {
  getQuestionView();
  nextTick(() => {
    // 监听事件总线的值变化事件
    console.log("FormBuilder 正在注册事件监听器");
    EventBus.on("component-value-change", handleEventBusValueChange);
    console.log("FormBuilder 事件监听器注册完成");
  });
});

// 组件卸载时清理事件监听器
onUnmounted(() => {
  EventBus.off("component-value-change", handleEventBusValueChange);
});

const route = useRoute();

// 问卷名称
const questionName = ref<string>("");

// 预览组件数据
const components = ref<CanvasComponent[]>([]);

// 表单引用
const formRef = ref<FormInstance>();

// 表单数据
const previewData = ref<Record<string, any>>({});

// 互斥状态管理
const mutexState = ref<Map<string, boolean>>(new Map());

// 选项关联状态管理
const relateState = ref<RelateConfig[]>([]);

// 获取问卷数据
const getQuestionView = async () => {
  const response = await getQuestionById({ id: route.query.id });
  questionName.value = response.name;

  if (response && response.question) {
    // 解析问卷数据
    const questionData = JSON.parse(response.question);
    if (Array.isArray(questionData)) {
      components.value = questionData;
      initPreviewData();
      checkMutexRules();
      checkRelateRules();
      ElMessage.success("问卷数据加载成功");
    } else {
      ElMessage.warning("问卷数据格式不正确");
    }
  } else {
    ElMessage.warning("未找到问卷数据");
  }
};

// 初始化预览数据
const initPreviewData = () => {
  previewData.value = {};

  // 处理顶层组件（排除有parentId的组件）
  const topLevelComponents = components.value.filter(
    (component) => !component.parentId
  );
  // 递归处理组件，包括栅格组件的children
  const processComponents = (components: any[]) => {
    components.forEach((component) => {
      if (component.type === "grid" && component.children) {
        // 如果是栅格组件，递归处理其children
        processComponents(component.children);
      } else {
        // 普通组件，初始化默认值
        const key = component.props?.field;
        if (key && component.type !== "grid" && component.type !== "divider") {
          previewData.value[key] = getDefaultValue(component.type);
        }
      }
    });
  };
  processComponents(topLevelComponents);
};

// 获取组件默认值
const getDefaultValue = (type: string): any => {
  // 统一按照 input 组件的标准，所有组件默认值都为空字符串
  switch (type) {
    case "checkbox":
      return []; // 多选框保持数组类型
    case "radio":
      return ""; // 单选框改为空字符串
    case "select":
      return ""; // 下拉选择改为空字符串
    case "number":
      return ""; // 数字输入改为空字符串
    case "date":
      return ""; // 日期选择保持空字符串
    default:
      return ""; // 其他所有组件都为空字符串
  }
};

// 获取组件样式（模拟画布布局）
const getComponentStyle = (component: CanvasComponent) => {
  // 计算组件宽度
  let componentWidth: string;
  if (component.props.widthType === "custom" && component.props.customWidth) {
    componentWidth = component.props.customWidth + "px";
  } else if (component.props.widthType === "full") {
    componentWidth = "100%";
  } else {
    componentWidth = component.size.width + "px";
  }

  return {
    position: "relative" as const,
    // left: component.position.x + "px",
    // top: component.position.y + "px",
    width: componentWidth,
    // height: component.size.height + "px",
    zIndex: 1,
  };
};

// 检查互斥规则
const checkMutexRules = () => {
  console.log("开始检查互斥规则...");
  // 重置所有组件的隐藏状态
  mutexState.value.clear();

  // 递归处理所有组件（包括栅格内的子组件）
  const processAllComponents = (components: CanvasComponent[]) => {
    components.forEach((component) => {
      if (component.type === "grid" && component.children) {
        // 如果是栅格组件，递归处理其children
        processAllComponents(component.children);
      } else {
        // 检查普通组件的互斥规则
        if (
          component.props.mutexConfig?.enabled &&
          component.props.mutexConfig.rules
        ) {
          const key = component.props.field || component.id;
          const currentValue = previewData.value[key];
          console.log(
            `检查组件 ${component.props.label} (${key}) 的值:`,
            currentValue
          );

          const matchingRule = component.props.mutexConfig.rules.find(
            (rule: MutexRule) => rule.value === currentValue
          );

          if (matchingRule) {
            console.log(
              `找到匹配规则，隐藏组件:`,
              matchingRule.hiddenComponents
            );
            // 隐藏指定的组件（直接使用组件ID）
            matchingRule.hiddenComponents.forEach(
              (hiddenComponentId: string) => {
                mutexState.value.set(hiddenComponentId, true);
                console.log(`隐藏组件: ${hiddenComponentId}`);
              }
            );
          }
        }
      }
    });
  };

  // 处理顶层组件
  const topLevelComponents = components.value.filter(
    (component) => !component.parentId
  );
  processAllComponents(topLevelComponents);

  console.log("互斥状态:", mutexState.value);
};

// 检查选项关联规则
const checkRelateRules = () => {
  console.log("开始检查选项关联规则...");
  // 重置所有组件的隐藏状态
  relateState.value = [];

  // 递归处理所有组件（包括栅格内的子组件）
  const processAllComponents = (components: CanvasComponent[]) => {
    components.forEach((component) => {
      if (component.type === "grid" && component.children) {
        // 如果是栅格组件，递归处理其children
        processAllComponents(component.children);
      } else {
        // 检查普通组件的选项关联规则

        if (
          component.props?.relateConfig?.enabled &&
          component.props?.relateConfig?.rules
        ) {
          relateState.value.push(component.props?.relateConfig);
        }
      }
    });
  };

  processAllComponents(components.value);

  console.log("选项关联状态:", relateState.value);
};

// 处理组件值变化
const handleEventBusValueChange = (payload: {
  field: string;
  value: any;
  componentId?: string;
}) => {
  console.log(
    "FormBuilder 事件总线接收到值变化:",
    payload.field,
    payload.value,
    payload.componentId
  );
  if (payload.componentId) {
    previewData.value[payload.field] = payload.value;
    // 重新检查互斥规则
    checkMutexRules();
    // 重新检查选项关联规则
    checkRelateRules();
    // 处理关联项options
    setComponentOptions(payload);
  }
};

// 设置组件选项（调试用）
const setComponentOptions = (payload: {
  field: string;
  value: any;
  componentId?: string;
}) => {
  console.log("组件值变化:", {
    componentId: payload.componentId,
    currentComponentId: payload.componentId,
    label: payload.field,
    value: payload.value,
    relateState: relateState.value,
  });

  // 检查 componentId 是否存在
  if (payload.componentId) {
    relateState.value.forEach((relateItem: any) => {
      // 这里可以添加处理 rules 的逻辑
      if (relateItem.dependentComponentId === payload.componentId) {
        // 处理选项更新逻辑
        const handleSetOptions = (components: any) => {
          components.forEach((component: any) => {
            if (component.type === "grid") {
              handleSetOptions(component.children);
            } else {
              if (component.id === relateItem.currentComponentId) {
                previewData.value[component.props.field] = getDefaultValue(
                  component.type
                );
                if (
                  !payload.value ||
                  payload.value === "" ||
                  payload.value === null ||
                  payload.value === undefined
                ) {
                  // 当值为空时，恢复原始选项
                  component.props.options = relateItem.currentComponentOptions;
                } else {
                  // 查找匹配的规则
                  const ruleItem = relateItem.rules.find(
                    (item: any) => item.currentOptionValue === payload.value
                  );
                  if (ruleItem) {
                    // 应用关联规则的选项
                    component.props.options = ruleItem.dependentOptions;
                  } else {
                    // 没有匹配规则时，保持原始选项
                    component.props.options =
                      relateItem.currentComponentOptions;
                  }
                }
              }
            }
          });
        };
        handleSetOptions(components.value);
      }
    });
  }
};

// 检查组件是否被隐藏
const isComponentHidden = (componentId: string): boolean => {
  return mutexState.value.get(componentId) || false;
};

// 重置表单
const handleReset = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  initPreviewData();
};

// 提交表单
const handleSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      console.log("提交表单数据:", previewData.value);
    }
  });
};
</script>

<style lang="scss">
.form-preview {
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  .header {
    margin-bottom: 0px;
    padding: 20px;
    border-bottom: 1px solid #e4e7ed;
    text-align: center;
    .question-name {
      font-size: 18px;
      color: #606266;
      font-weight: bolder;
    }
  }
  .actions {
      display: flex;
      gap: 10px;
      padding: 20px;
      justify-content: center;
      border-top: 1px solid #e4e7ed;
    }
  .preview-box {
    overflow: auto;
    flex: 1;
    padding: 10px 0;
    .preview-canvas {
      position: relative;
      background: white;
      border-radius: 4px;
      overflow: auto;
      width: 910px;
      padding: 20px;
      padding-bottom: 0;
      // min-height: 1100px;
      margin: 0 auto;
      box-shadow: 1px 1px 10px 1px #ccc;
      box-sizing: border-box;
      
      // 移动端适配
      @media (max-width: 768px) {
        &.preview-canvas{
          width: 100%;
          margin: 0;
          box-shadow: none;
          border-radius: 0;
          padding: 0 10px;
          .form-component{
            padding: 0!important;
            .el-form-item__label{
              // padding-right: 0!important;
            }
          }
        }
      }
    }

    .preview-component {
      border: 1px dashed transparent;
      border-radius: 4px;
      margin-bottom: 10px;
      &:hover {
        border-color: transparent;
      }
      .el-radio-group{
        gap: 10px;
        
        .el-radio{
          margin-right: 0;
        }
      }
    }
  }
}

// 全局样式覆盖
:deep(.form-component) {
  &:hover {
    border: none !important;
    outline: none !important;
  }
}

:deep(.grid-item) {
  &:hover {
    background-color: transparent !important;
  }
}
</style>
